import { getUserAddress, setUserPhone, getUserCertify } from '../../services/user'
import { initOrder, updateOrder, submitFreeze, payOrder, getAvailableCoupons } from '../../services/order'
import { dateFormat } from '../../utils/date'
import { priceToYuan } from '../../utils/utils'

const app = getApp()
const DAY = 24 * 60 * 60 * 1e3

const translateSettleInfo = (settleInfo) => {
  const settleInfoStr = {}
  Object.keys(settleInfo).forEach(key => {
    settleInfoStr[key] = priceToYuan(settleInfo[key])
  })
  return settleInfoStr
}

Page({
  data: {
    // 是否已完成押金抵扣流程
    preOrderId: '',

    showBottom: false,
    protocolChecked: false,
    pushdata: {},
    addressInfo: undefined,
    
    settleInfo: {},
    orderInfo: {},
    settleInfoStr: {},
    userInfo: {},

    notes: '',
    
    couponList: [],
    useCouponId: 0,
    showcoupontitle: '',

    useScore: 0,
    useWallet: false,

    showBottom2: false,

    rentDay: 0,

    rentStart: '',
    rentEnd: '',
  },
  async onShow() {
    const now = new Date()
    const rentStart = now.setHours(23,59,59,59) + DAY
    this.setData({
      rentStart: dateFormat(rentStart, 'MM月dd日'),
      rentEnd: dateFormat(rentStart + this.data.rentDay * DAY, 'MM月dd日')
    })

    if (this.data.rentDay < app.globalData.playforminfo.startRentDay || this.data.rentDay > 365) {
      my.showToast({ content: '订单参数异常' })
    } else {
      my.showLoading()

      await app.silenceLogin()

      await this.initOrder()
      await this.getUserAddress()

      my.hideLoading()
    }
  },
  onLoad(event) {
    event = {
      "goodsName": "IPhone13 ProMax 9.9新手机",
      "id": "617b81995fc4f196255b9ce3",
      "rentDay": 7,
      "skuId": "白/256G",
      "skuImage": "http://gbuy.oss-cn-shanghai.aliyuncs.com/moon/KyxaBuEY0_9gt2u5.jpeg",
      "specName": "已选择白/256G 15天租用"
    }

    this.setData({ pushdata: event, rentDay: event.rentDay })

    my.setNavigationBar({
      title: '确认订单',
      backgroundColor: '#4BA3F9'
    })
  },
  onPopupClose() {
    this.setData({
      showBottom: false,
      showBottom2: false
    });
  },
  onPopupOpen() {
    this.setData({
      showBottom: true,
    });
  },
  onNotesInput({ detail: { value } }) {
    this.setData({ notes: value })
  },
  verifyOrder() {
    if (Object.keys(this.data.addressInfo).length <= 0) {
      my.showToast({
        type: 'fail',
        content: '请填写收货地址',
        duration: 2000,
      })
      return false
    }
    
    if (!this.data.protocolChecked) {
      my.showToast({
        type: 'fail',
        content: '请阅读协议',
        duration: 2000,
      })
      return false
    }

    return true
  },
  submitOrder() {
    if (this.verifyOrder() === false) {
      return false
    }
    
    if (!this.data.preOrderId) {
      // 调起押金流程
      this.callPayDeposit()
    } else {
      this.callPayOrder()
    }
  },
  async callPayOrder() {
    const { preOrderId } = this.data

    const { code, data } = await payOrder({ preOrderId })

    if (code !== 0) return false
  
    const that = this

    my.tradePay({
      tradeNO: data.payParams.tradeNo,
      success: function (resultAli) {
        if (resultAli.resultCode == 9000) {
          // 重置押金状态
          that.setData({ preOrderId: '' })
          
          my.showToast({
            type: 'success',
            content: '支付成功',
            duration: 2000,
          })

          setTimeout(() => {
            my.navigateTo({
              url: '/pages/my-order/my-order'
            })
          }, 2000)
        } else {
          my.showToast({
            type: 'fail',
            content: '支付失败',
            duration: 2000,
          })

          setTimeout(() => {
            my.navigateTo({
              url: '/pages/my-order/my-order'
            })
          }, 2000)
        }
      },
      fail: function (res) {
        my.showToast({ type: 'fail', content: '支付服务异常 请退出重试' })
      },
    })
  },
  async callPayDeposit() {
    const { 
      addressInfo: address_info, 
      goodsInfo: goods_info, 
      useCouponId: use_coupon, 
      useWallet: use_wallet, 
      useScore: use_score,
      rentDay: rent_time,
    } = this.data
    
    const { code, data } = await submitFreeze({ address_info, goods_info: [goods_info], rent_time, use_coupon, use_wallet, use_score, rent_time })

    if (code != 0) return false

    if (!data.pre_order_id) {
      return my.showToast({
        type: 'fail',
        content: '押金冻结失败 稍后重试',
        duration: 2000,
      })
    }

    my.tradePay({
      orderStr: data.orderStr,
      success: (freezeRes) => {
        let resultAli = freezeRes
        if (resultAli.resultCode == 9000) {
          my.showToast({
            type: 'success',
            content: '押金冻结成功 现在支付租金吧',
            duration: 3000,
          })

          this.setData({ preOrderId: data.pre_order_id })
        } else {
          my.showToast({
            type: 'fail',
            content: '押金冻结失败',
            duration: 2000,
          })
        }
      },
      fail: (res) => {
        my.showToast({
          type: 'fail',
          content: '押金冻结失败',
          duration: 2000,
        })
      }
    })
  },
  onGetAuthorize() {
    if (this.verifyOrder() === false) {
      return false
    }
    
    const { userInfo } = this.data

    my.getPhoneNumber({
      success: (res) => {
        let encryptedData = JSON.parse(res.response).response
        setUserPhone({ encryptedData }).then(({code, data}) => {
          if (code == 0) {
            userInfo.phone = data.phone
            this.setData({ userInfo })
            this.submitOrder()
          }
        })
      },
      fail: (res) => {
        my.showToast({
          type: 'fail',
          content: '授权失败',
          duration: 2000,
        })
      },
    })
  },
  async initOrder() {
    const { id, skuId, rentDay, amount = 1 } = this.data.pushdata

    let param = {
      rent_time: parseInt(rentDay),
      goods_info: [{
        attribute_name: skuId,
        id: id,
        amount,
      }]
    }
    const { code, data } = await initOrder(param)
    if (code != 0) return false
    
    const { goods_info: [goodsInfo], settle_info: settleInfo, user_info: userInfo, deposit_info: depositInfo , ...orderInfo } = data

    const settleInfoStr = translateSettleInfo(settleInfo)

    this.setData({
      orderInfo,
      goodsInfo,
      settleInfo,
      userInfo,
      settleInfoStr,
      depositInfo: {
        total_amount: priceToYuan(depositInfo.total_amount)
      }
    })

    this.getAvailableCoupons(data.settle_info)
  },
  async updateOrderInfo() {
    const { settleInfo, useCouponId, useScore, useWallet } = this.data
    my.showLoading()
    const { code, data } = await updateOrder({ 
      use_score: useScore, 
      use_wallet: useWallet, 
      use_coupon: useCouponId, 
      settle_info: settleInfo 
    })
    my.hideLoading()
    if (code != 0) return false

    this.setData({ settleInfo: data.settle_info, settleInfoStr: translateSettleInfo(data.settle_info) })
  },
  async getAvailableCoupons(settle_info) {
    const { code, data } = await getAvailableCoupons({ settle_info })
    if (code != 0) return false

    if (data.coupon_list != undefined) {
      this.setData({ 
        showcoupontitle: `共 ${data.coupon_list.length} 张优惠券`, 
        couponList: data.coupon_list.map((item, index) => ({
          id: item.id,
          couponAmount: priceToYuan(item.discount),
          minPurchase: priceToYuan(item.threshold),
          couponStart: dateFormat(item.start_date),
          couponEnd: dateFormat(item.end_date),
          couponName: item.name,
          action: 3,
        }))
      })
    }
  },
  addressClick() {
    my.navigateTo({
      url: '/pages/addAddress/addAddress?addressInfo=' + JSON.stringify(this.data.addressInfo)
    })
  },
  agreementClick() {
    my.downloadFile({
      url: "https://cw.mixue.ink/upload/xieyi.pdf",
      success({ apFilePath }) {
        my.hideLoading();
        my.openDocument({
          filePath: apFilePath,
          fileType: 'pdf',
          success: (res) => {
            console.log(res);
          },
          fail: (res) => {
            console.log(res);
          }
        })
      }
    })
  },
  onProtocolCheckChange(e) {
    this.setData({ protocolChecked: e.detail.value })
  },
  async getUserAddress() {
    const { code, data } = await getUserAddress()
    if (code != 0) return false

    if (data && data.detail) {
      this.setData({ addressInfo: data })
    }
  },
  selectcoupon({ target: { dataset: { id, name } } }) {
    this.setData({ 
      useCouponId: id, 
      showBottom: false, 
      showcoupontitle: name ? name : `共 ${this.data.couponList.length} 张优惠券` 
    })
    
    this.updateOrderInfo()
  },
});
